package system.ui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginRegisterPage extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton registerButton;

    private static final String URL = "jdbc:mysql://localhost:3306/java-swing";
    private static final String USER = "root";
    private static final String PASSWORD = "root";

    public LoginRegisterPage() {
        setTitle("用户登录和注册");
        setSize(450, 350);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 居中显示

        JPanel panel = new JPanel(new BorderLayout());

        // 登录面板
        JPanel loginPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbcLogin = new GridBagConstraints();
        gbcLogin.gridx = 0;
        gbcLogin.gridy = 0;
        gbcLogin.insets = new Insets(5, 5, 5, 5);

        JLabel usernameLabel = new JLabel("用户名:");
        loginPanel.add(usernameLabel, gbcLogin);

        gbcLogin.gridx++;
        usernameField = new JTextField(20);
        loginPanel.add(usernameField, gbcLogin);

        gbcLogin.gridx = 0;
        gbcLogin.gridy++;
        JLabel passwordLabel = new JLabel("密码:");
        loginPanel.add(passwordLabel, gbcLogin);

        gbcLogin.gridx++;
        passwordField = new JPasswordField(20);
        loginPanel.add(passwordField, gbcLogin);

        gbcLogin.gridx = 0;
        gbcLogin.gridy++;
        gbcLogin.gridwidth = 2;
        gbcLogin.fill = GridBagConstraints.HORIZONTAL;
        loginButton = new JButton("登录");
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = usernameField.getText().trim();
                String password = new String(passwordField.getPassword());

                if (validateLogin(username, password)) {
                    JOptionPane.showMessageDialog(LoginRegisterPage.this, "登录成功");
                    // 这里可以添加登录成功后的操作，如打开主界面等
                    dispose();
                    SwingUtilities.invokeLater(StudentManagementSystem::new);
                } else {
                    JOptionPane.showMessageDialog(LoginRegisterPage.this, "登录失败，请检查用户名和密码", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        loginPanel.add(loginButton, gbcLogin);

        // 注册面板
        JPanel registerPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbcRegister = new GridBagConstraints();
        gbcRegister.gridx = 0;
        gbcRegister.gridy = 0;
        gbcRegister.insets = new Insets(5, 5, 5, 5);

        JLabel newUsernameLabel = new JLabel("新用户名:");
        registerPanel.add(newUsernameLabel, gbcRegister);

        gbcRegister.gridx++;
        JTextField newUsernameField = new JTextField(20);
        registerPanel.add(newUsernameField, gbcRegister);

        gbcRegister.gridx = 0;
        gbcRegister.gridy++;
        JLabel newPasswordLabel = new JLabel("新密码:");
        registerPanel.add(newPasswordLabel, gbcRegister);

        gbcRegister.gridx++;
        JPasswordField newPasswordField = new JPasswordField(20);
        registerPanel.add(newPasswordField, gbcRegister);

        gbcRegister.gridx = 0;
        gbcRegister.gridy++;
        JLabel confirmPasswordLabel = new JLabel("确认密码:");
        registerPanel.add(confirmPasswordLabel, gbcRegister);

        gbcRegister.gridx++;
        JPasswordField confirmNewPasswordField = new JPasswordField(20);
        registerPanel.add(confirmNewPasswordField, gbcRegister);

        gbcRegister.gridx = 0;
        gbcRegister.gridy++;
        gbcRegister.gridwidth = 2;
        gbcRegister.fill = GridBagConstraints.HORIZONTAL;
        registerButton = new JButton("注册");
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String newUsername = newUsernameField.getText().trim();
                String newPassword = new String(newPasswordField.getPassword());
                String confirmNewPassword = new String(confirmNewPasswordField.getPassword());

                if (newUsername.isEmpty() || newPassword.isEmpty() || confirmNewPassword.isEmpty()) {
                    JOptionPane.showMessageDialog(LoginRegisterPage.this, "请填写完整信息", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (!newPassword.equals(confirmNewPassword)) {
                    JOptionPane.showMessageDialog(LoginRegisterPage.this, "确认密码不匹配", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (checkUserExists(newUsername)) {
                    JOptionPane.showMessageDialog(LoginRegisterPage.this, "用户名已存在", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (registerUser(newUsername, newPassword)) {
                    JOptionPane.showMessageDialog(LoginRegisterPage.this, "注册成功");
                    // 注册成功后清空表单
                    newUsernameField.setText("");
                    newPasswordField.setText("");
                    confirmNewPasswordField.setText("");
                } else {
                    JOptionPane.showMessageDialog(LoginRegisterPage.this, "注册失败，请稍后再试", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        registerPanel.add(registerButton, gbcRegister);

        // 创建切换卡片面板
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("登录", loginPanel);
        tabbedPane.addTab("注册", registerPanel);

        panel.add(tabbedPane, BorderLayout.CENTER);

        add(panel);
    }

    private boolean validateLogin(String username, String password) {
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
            String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
            try (PreparedStatement statement = conn.prepareStatement(sql)) {
                statement.setString(1, username);
                statement.setString(2, password);
                ResultSet result = statement.executeQuery();
                return result.next(); // 如果有匹配的用户记录，则返回true
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库连接错误", "错误", JOptionPane.ERROR_MESSAGE);
        }
        return false;
    }

    private boolean registerUser(String username, String password) {
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
            String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
            try (PreparedStatement statement = conn.prepareStatement(sql)) {
                statement.setString(1, username);
                statement.setString(2, password);
                int rowsInserted = statement.executeUpdate();
                return rowsInserted > 0; // 如果插入成功，则返回true
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库连接错误", "错误", JOptionPane.ERROR_MESSAGE);
        }
        return false;
    }

    private boolean checkUserExists(String username) {
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
            String sql = "SELECT * FROM users WHERE username = ?";
            try (PreparedStatement statement = conn.prepareStatement(sql)) {
                statement.setString(1, username);
                ResultSet result = statement.executeQuery();
                return result.next(); // 如果找到匹配的用户名，则返回true
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库连接错误", "错误", JOptionPane.ERROR_MESSAGE);
        }
        return false;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                LoginRegisterPage page = new LoginRegisterPage();
                page.setVisible(true);
            }
        });
    }
}
